import React, { Component } from 'react';
import _ from 'underscore';

import Slider from 'lib/components/slider.jsx';

const percents = [
  {
    label: ' 1/64 ',
    value: 1
  },
  {
    label: ' 1/32 ',
    value: 2
  },
  {
    label: ' 1/16 ',
    value: 4
  },
  {
    label: ' 1/8 ',
    value: 8
  },
  {
    label: ' 1/4 ',
    value: 16
  },
  {
    label: ' 1/2 ',
    value: 32
  },
  {
    label: '1/1',
    displayText: '全量',
    value: 64
  }
]; // percents

export default class PercentSilder extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      value: _.findIndex(percents, p => p.value === props.value)
    }; // state

    this.valueChangedHandler = this.valueChangedHandler.bind(this);
  }

  valueChangedHandler(value) {
    this.setState({ value: value }, () =>
      this.props.valueChanged(percents[this.state.value].value));
  } // valueChangedHandler

  componentWillReceiveProps(nextProps) {
    this.setState({ value: _.findIndex(percents, p => p.value === nextProps.value) });
  } // componentWillReceiveProps

  render() {
    let current = percents[this.state.value];
    return (
      <div className={ this.props.className } style={ this.props.style }>
        <div style={{
          display: 'inline-block',
          width: this.props.width
        }}>
          <Slider
            min={ 0 }
            max={ 6 }
            onChange={ this.valueChangedHandler }
            value={ this.state.value } />
        </div>
        <div style={{
          display: 'inline-block',
          marginLeft: 10
        }}>
          <span key={ this.state.value } data-tip={ `抽样${ current.displayText || current.label }的数据` }>
            { current.label.trim() }
          </span>
        </div>
      </div>
    );
  }; // render
}

PercentSilder.defaultProps = {
  className: '',
  style: {},
  width: 100,
  value: 64,
  valueChanged: value => {}
} // defaultProps
